/**
 * 3. 无重复字符的最长子串
 * https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 */

/**
 * @param {string} s
 * @return {number}
 */
function lengthOfLongestSubstring(s) {
  if (!s.length) {
    return 0;
  }
  const map = new Array(128).fill(-1);
  let max = 1;
  let start = 0;
  map[s.charCodeAt(0)] = 0;
  for (let i = 1; i < s.length; i += 1) {
    const code = s.charCodeAt(i);
    if (map[code] >= 0) {
      const nextStart = map[code] + 1;
      for (let j = map[code]; j >= start; j -= 1) {
        map[s.charCodeAt(j)] = -1;
      }
      start = nextStart;
    } else {
      const length = i - start + 1;
      if (length > max) {
        max = length;
      }
    }
    map[code] = i;
  }
  return max;
}

console.log(lengthOfLongestSubstring('abcabcbb') === 3);
console.log(lengthOfLongestSubstring('bbbbb') === 1);
console.log(lengthOfLongestSubstring('pwwkew') === 3);
